export class ConnectionManager {
  constructor(app) {
    this.app = app;
    this.socket = null;
    this.retryCount = 0;
    this.maxRetries = 5;
    this.retryDelay = 3000;
  }

  connectToServer() {
    this.app.domManager.updateConnectionStatus('connecting');

    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const host = window.location.host;
    this.socket = new WebSocket(`${protocol}//${host}`);
    this.socket.binaryType = 'arraybuffer';

    this.setupSocketListeners();
  }

  setupSocketListeners() {
    this.socket.onopen = () => {
      this.retryCount = 0;

      if (this.app.nickname) {
        this.sendMessage({
          type: 'setNickname',
          nickname: this.app.nickname
        });
        this.app.domManager.hideNicknameModal();
      } else {
        this.app.domManager.showNicknameModal();
      }
    };

    this.socket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if (data.type === 'system' && data.message.includes('成功')) {
        this.app.domManager.updateConnectionStatus('connected');
      }
      this.app.messageHandler.handleMessage(data);
    };

    this.socket.onclose = () => {
      this.app.domManager.updateConnectionStatus('disconnected');
      this.retryConnection();
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket error:', error);
      this.app.domManager.updateConnectionStatus('error');
      this.app.domManager.hideProgress();
    };
  }

  retryConnection() {
    if (this.retryCount < this.maxRetries) {
      this.retryCount++;
      setTimeout(() => {
        this.connectToServer();
      }, this.retryDelay);
    } else {
      alert('无法连接到服务器，请检查网络设置');
    }
  }

  sendMessage(data) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(data));
    }
  }
} 